<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('accessControl.roleManagement.batchAddTitle', { title: parameter.title })"
    :destroy-on-close="true"
    width="580px"
    draggable
  >
    <el-form class="drawer-multiColumn-form" label-width="100px">
      <el-form-item :label="t('accessControl.roleManagement.templateDownload')">
        <el-button type="primary" :icon="Download" @click="downloadTemp">{{
          t("accessControl.roleManagement.clickToDownload")
        }}</el-button>
      </el-form-item>
      <el-form-item :label="t('accessControl.roleManagement.fileUpload')">
        <el-upload
          action="#"
          class="upload"
          :drag="true"
          :limit="excelLimit"
          :multiple="false"
          :show-file-list="true"
          :http-request="uploadExcel"
          :before-upload="beforeExcelUpload"
          :on-exceed="handleExceed"
          :on-success="excelUploadSuccess"
          :on-error="excelUploadError"
          :accept="parameter.fileType!.join(',')"
        >
          <slot name="empty">
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">{{ t("accessControl.roleManagement.dragFileHere") }}</div>
          </slot>
          <template #tip>
            <slot name="tip">
              <div class="el-upload__tip">{{ t("accessControl.roleManagement.uploadTip", { size: parameter.fileSize }) }}</div>
            </slot>
          </template>
        </el-upload>
      </el-form-item>
      <!-- <el-form-item label="数据覆盖 :">
        <el-switch v-model="isCover" />
      </el-form-item> -->
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts" name="ImportExcel">
import { ref } from "vue";
import { useDownload } from "@/hooks/custemerDownload";
import { Download } from "@element-plus/icons-vue";
import { ElNotification, UploadRequestOptions, UploadRawFile } from "element-plus";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

export interface ExcelParameterProps {
  title: string; // 标题
  fileSize?: number; // 上传文件的大小
  fileType?: File.ExcelMimeType[]; // 上传文件的类型
  tempApi?: (params: any) => Promise<any>; // 下载模板的Api
  importApi?: (params: any) => Promise<any>; // 批量导入的Api
  getTableList?: () => void; // 获取表格数据的Api
}

// 是否覆盖数据
const isCover = ref(false);
// 最大文件上传数
const excelLimit = ref(1);
// dialog状态
const dialogVisible = ref(false);
// 父组件传过来的参数
const parameter = ref<ExcelParameterProps>({
  title: "",
  fileSize: 5,
  fileType: ["text/csv"]
});

// 接收父组件参数
const acceptParams = (params: ExcelParameterProps) => {
  parameter.value = { ...parameter.value, ...params };
  dialogVisible.value = true;
};

// Excel 导入模板下载
const downloadTemp = () => {
  if (!parameter.value.tempApi) return;
  useDownload(parameter.value.tempApi, t("accessControl.roleManagement.batchImportTemplate"), {}, true, ".zip");
};

// 文件上传
const uploadExcel = async (param: UploadRequestOptions) => {
  let excelFormData = new FormData();
  excelFormData.append("roleQueryDto.importFile", param.file);
  parameter.value.importApi!(excelFormData).then(res => {
    if (res != null && res != "") {
      res = res.replace("Total", t("accessControl.roleManagement.total"));
      res = res.replace("Insert", t("accessControl.roleManagement.insert"));
      res = res.replace("Update", t("accessControl.roleManagement.update"));
      res = res.replace("Failure", t("accessControl.roleManagement.failure"));
    }
    ElNotification({
      duration: 10000,
      title: t("accessControl.roleManagement.tips"),
      message: t("accessControl.roleManagement.importSuccess") + res.toString(),
      type: "success"
    });
  });

  parameter.value.getTableList && parameter.value.getTableList();
  dialogVisible.value = false;
};

/**
 * @description 文件上传之前判断
 * @param file 上传的文件
 * */
const beforeExcelUpload = (file: UploadRawFile) => {
  const isExcel = parameter.value.fileType!.includes(file.type as File.ExcelMimeType);
  const fileSize = file.size / 1024 / 1024 < parameter.value.fileSize!;
  if (!isExcel)
    ElNotification({
      title: t("accessControl.roleManagement.tips"),
      message: t("accessControl.roleManagement.onlyCSVAllowed"),
      type: "warning"
    });
  if (!fileSize)
    setTimeout(() => {
      ElNotification({
        title: t("accessControl.roleManagement.tips"),
        message: t("accessControl.roleManagement.fileSizeExceeded", { size: parameter.value.fileSize }),
        type: "warning"
      });
    }, 0);
  return isExcel && fileSize;
};

// 文件数超出提示
const handleExceed = () => {
  ElNotification({
    title: t("accessControl.roleManagement.tips"),
    message: t("accessControl.roleManagement.maxOneFile"),
    type: "warning"
  });
};

// 上传错误提示
const excelUploadError = () => {
  ElNotification({
    title: t("accessControl.roleManagement.tips"),
    message: t("accessControl.roleManagement.batchAddFailed", { title: parameter.value.title }),
    type: "error"
  });
};

// 上传成功提示
const excelUploadSuccess = (res: any) => {
  // ElNotification({
  //   title: t('accessControl.roleManagement.tips'),
  //   message: t('accessControl.roleManagement.batchAddSuccess', { title: parameter.value.title }),
  //   type: "success"
  // });
};

defineExpose({
  acceptParams
});
</script>
<style lang="scss" scoped>
@import "./index";
</style>
